package com.persagy.iot.utils

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}

import java.util.Properties
import scala.io.BufferedSource

object KafkaUtil {

  val dev_host: String = "192.168.4.7:9092,192.168.4.8:9092,192.168.4.9:9092"
  val test_host: String = "192.168.100.84:9092,192.168.100.75:9092,192.168.100.147:9092"
  val topic: String = "iot_data"
  val file_path: String = "/Users/king/Documents/persagy/dw/log.log2021-01-11-15.log";

  def kafkaConsumerProperties(): Properties = {
    val properties = new Properties()
    properties.setProperty("bootstrap.servers", dev_host)
    properties.setProperty("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
    properties.setProperty("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
    properties.setProperty("auto.offset.reset", "latest")
    properties
  }

  def kafkaProducerProperties(): Properties = {
    val properties = new Properties()
    properties.setProperty("bootstrap.servers", dev_host)
    properties.setProperty("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
    properties.setProperty("value.serializer", "org.apache.kafka.common.serialization.StringSerializer")
    properties
  }

  def sendMessageToKafka(topic: String): Unit = {

    /** 创建一个 KafkaProducer，发送数据 */
    val producer = new KafkaProducer[String, String](kafkaProducerProperties())

    /** 从文件读取数据，逐条发送 */
    val bufferedSource: BufferedSource = scala.io.Source.fromFile(file_path)

    for (line <- bufferedSource.getLines()) {
      val record = new ProducerRecord[String, String](topic, line)
      println(line.toString)
      producer.send(record)
//      Thread.sleep(500L)
    }
  }

}
